<template>
  <canvas ref="barChart" width="600" height="400"></canvas>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      required: true
    }
  },
  mounted() {
    this.drawBarChart();
  },
  methods: {
    drawBarChart() {
      const canvas = this.$refs.barChart;
      const ctx = canvas.getContext('2d');
      const chartHeight = canvas.height - 50;
      const chartWidth = canvas.width - 100;
      const maxValue = Math.max(...this.data.map(item => item.value));
      const barWidth = chartWidth / this.data.length * 0.8;
      const gap = chartWidth / this.data.length * 0.2;

      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制坐标轴
      ctx.beginPath();
      ctx.moveTo(50, 0);
      ctx.lineTo(50, chartHeight);
      ctx.lineTo(canvas.width, chartHeight);
      ctx.fillText("金额(元)", 30, 20); // 填写具体单位
      ctx.strokeStyle = '#000';
      ctx.stroke();

      // 新增：添加X轴描述
      ctx.textAlign = "center";
      ctx.fillStyle = "#000";
      ctx.fillText("日期", canvas.width-20, canvas.height-30 );


      // 绘制柱子
      this.data.forEach((item, index) => {
        const x = 50 + gap / 2 + index * (barWidth + gap);
        const height = (item.value / maxValue) * (chartHeight - 50);

        // 柱体
        ctx.fillStyle = item.color;
        ctx.fillRect(x, chartHeight - height, barWidth, height);

        // 数值标签
        ctx.fillStyle = '#000';
        ctx.textAlign = 'center';
        ctx.fillText(item.value, x + barWidth / 2, chartHeight - height - 5);

        // 底部标签
        ctx.fillText(item.label, x + barWidth / 2, chartHeight + 20);
      });
    }
  },
  watch: {
    data: {
      handler() {
        this.drawBarChart();
      },
      deep: true
    }
  }
}
</script>
